#include "stdafx.h"

#include <future>
#include <thread>

#include "ClientManager.h"
#include "TaskManager.h"
#include "Session.h"

#include "TCpu.h"
#include "CheckRegister.h"
#include "HelperFunctions.h"
#include "Constants.h"

TCpu::TCpu(QObject *parent)
    : QObject(parent)
{
    if (_instance)
        delete _instance;
    _instance = this;
}

TCpu::~TCpu()
{

}

void TCpu::pause()
{
    _paused = true;
    playSound(Constants::audioPath.taskPaused);
}

void TCpu::resume()
{
    _paused = false;
    playSound(Constants::audioPath.taskResumed);
}

void TCpu::on(int channel, const QString &type, QVariantMap obj)
{
    CHECK_REGISTER();
    const auto &cs = tasks.at(channel);
    TaskProcessFunctionType func = cs.at(type.toStdString());

    std::async([=]()
    {
        auto span = std::chrono::milliseconds(10);
        while (this->_paused)
            std::this_thread::sleep_for(span);
        func(obj);
    });
}

void TCpu::setOn(int channel, const QString &type, TaskProcessFunctionType func)
{
    CHECK_REGISTER();
    auto &channelTasks = tasks[channel];
    channelTasks.emplace(type.toStdString(), func);
}

TCpu * TCpu::instance()
{
    if (_instance == nullptr)
        _instance = new TCpu;
    return _instance;
}

TCpu * TCpu::_instance = nullptr;
